<template>
  <div>
    <!-- input 把图片加载进来 -->
    <input type="file" @change="change" accept="image/*" name="image" />
    <button @click="peropp">裁剪</button>
    <button @click="send">压缩并上传</button>
    <!-- 插件 -->
    <div style="height:300px">
      <vue-cropper
        v-show="!cropImg"
        ref="cropper"
        :aspect-ratio="10 / 10"
        :src="imgSrc"
        preview=".preview"
      />
    </div>
    <img v-bind:src="cropImg" v-show="cropImg" alt="" />
  </div>
</template>

<script>
import  VueCropper  from "vue-cropperjs";
import 'cropperjs/dist/cropper.css'
import {compress} from '@/utils/compressImg'
import {upLoad}  from '@/api/user'
export default {
  name: "App",
  data() {
    return {
      cropImg: "",
      imgSrc: ""
    };
  },
  methods: {
    //   压缩
    send:async function() {
        // 1.先把base64转成blob数据类型，
        var arr = this.cropImg.split(','),
				mime = arr[0].match(/:(.*?);/)[1],
				bstr = atob(arr[1]),
				n = bstr.length,
				u8arr = new Uint8Array(n)
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n)
			} 
		const ImgData =  new Blob([u8arr], { type: mime })
         const result=await compress(ImgData)
        // 2.forData对象把图片压缩的数据插入进去
         let data=new FormData()
         data.append('img',result,'head.jpg')
        // 3.ajax上传
        upLoad(data).then((res)=>{

        })
    },
    //   裁剪方法
    peropp() {
      this.cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL();
    },
    change(e) {
      const file = e.target.files[0];
      if (!file) return console.error("没有选择图片");
      if(file.type.indexOf('image/')===-1){
          this.$message.error('请选择一个头像')
          return false
      }
    //   如果上传了图片
    const reader=new FileReader()
    reader.onload=(e)=>{
        this.imgSrc=e.target.result
        this.$refs.cropper.replace(e.target.result)
    }
    // 执行一下加载
    reader.readAsDataURL(file)
    return false
    this.imgSrc='Blob'
    this.$refs.cropper.replace(require('@/assets/image1.jpg'))
    }
  },
  components: {
    VueCropper
  }
};
</script>

<style></style>
